// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: leon

#pragma once

#include <map>
#include <string>
#include <vector>

#include "coin2/exchange/base/executor_util/market_ts.h"
#include "coin2/exchange/base/feed/processor.h"
#include "coin2/exchange/feed.pb.h"
#include "coin2/exchange/gateio/symbology/product.h"

namespace coin2::exchange::gateio::feed_v4 {
namespace impl {

using coin2::exchange::feed::WebsocketConfig;

class GateioRequestGenerator : public base::feed::RequestGenerator {
 public:
 explicit GateioRequestGenerator(const WebsocketConfig* ws_config)
      : config_(ws_config) {}

  std::vector<std::string> GenerateRequests(
    const std::vector<std::string>& channels,
    const std::vector<std::string>& symbols,
    const std::map<std::string, std::string>& channel_templates,
    const std::string& request_template) override {
    std::vector<std::string> reqs;
    std::vector<std::string> ch = channels;

    auto timestamp = MarketTimestampProvider::GetTimestamp();
    std::string time = std::to_string(timestamp / 1'000'000'000L);
    std::string subscription_template = request_template;
    boost::replace_all(subscription_template, "{time}", time);

    std::vector<std::string> ch_kline;
    auto iter = ch.begin();
    while (iter != ch.end()) {
      if (StringStartsWith(*iter, "kline_rest")) {
        ch_kline.push_back(*iter);
        iter = ch.erase(iter);
      } else {
        iter++;
      }
    }
    if (!ch_kline.empty()) {
      auto timestamp = MarketTimestampProvider::GetTimestamp();
      boost::posix_time::ptime round_time = TimestampRoundHour(timestamp);
      for (auto& ch_k : ch_kline) {
        std::string c = channel_templates.at(ch_k);
        int64_t granularity = GetGranularity(c);
        for (auto& symbol : symbols) {
          std::vector<std::pair<int64_t, int64_t>> durations;
          bool long_query = base::feed::RequestGenerator::CheckLongQuery(
              round_time, symbol, ch_k, &last_long_query_time_);
          if (long_query) {
            durations = base::feed::RequestGenerator::GetDurations(
                config_->kline_length(), config_->kline_start(), config_->kline_end(),
                granularity, 900);
          } else {
            // query small data
            durations = base::feed::RequestGenerator::GetDurations(
                "3", "", "",granularity, 900);
          }
          for (auto& d : durations) {
            std::string c_copy = c;
            boost::replace_all(c_copy, "{}", symbol);
            boost::replace_all(c_copy, "{start}", ToKlineTimeString(d.first));
            boost::replace_all(c_copy, "{end}", ToKlineTimeString(d.second));
            reqs.emplace_back(c_copy);
          }
        }
      }
    }

    std::vector<std::string> symbols_in_quotes;
    for (const auto& sym : symbols) {
      symbols_in_quotes.push_back("\"" + sym + "\"");
    }
    std::string symbol_list = boost::algorithm::join(symbols_in_quotes, ",");

    std::vector<std::string> support_array = {"bbo", "trade"};
    for (const auto& c : support_array) {
      auto it = std::find(ch.begin(), ch.end(), c);
      if (it != ch.end()) {
        std::string ch_template = channel_templates.at(c);
        boost::replace_all(ch_template, "{}", symbol_list);
        std::string s = subscription_template;
        boost::replace_all(s, "{channel}", ch_template);
        reqs.push_back(s);
        ch.erase(it);
      }
    }

    std::vector<std::string> reqs_others = RequestGenerator::GenerateRequests(
        ch, symbols, channel_templates, subscription_template);
    reqs.insert(reqs.end(), reqs_others.begin(), reqs_others.end());

    return reqs;
  }

 private:
  std::string ToKlineTimeString(int64_t timestamp) {
    return std::to_string(timestamp / 1'000'000'000LL);
  }

  int64_t GetGranularity(const std::string& channel) {
    if (channel.find("interval=1m&") != std::string::npos) {
      return (int64_t)60 * 1'000'000'000;
    } else if (channel.find("interval=5m&") != std::string::npos) {
      return (int64_t)300 * 1'000'000'000;
    } else if (channel.find("interval=15m&") != std::string::npos) {
      return (int64_t)900 * 1'000'000'000;
    } else if (channel.find("interval=1h&") != std::string::npos) {
      return (int64_t)3600 * 1'000'000'000;
    } else if (channel.find("interval=1d&") != std::string::npos) {
      return (int64_t)24 * 3600 * 1'000'000'000;
    } else {
      THROW() << "Unkonw new channel: " << channel;
    }

    return std::numeric_limits<int64_t>::quiet_NaN();
  }

  const WebsocketConfig* config_;
};

}  // namespace impl
using impl::GateioRequestGenerator;
}  // namespace coin2::exchange::gateio::feed_v4
